from apps.interface.pageConfig.baseViews import *
from apps.interface.client.dao import ClientDao
from apps.interface.advert.serializers import Advert, AdvertBaseSerializer
from apps.interface.pageConfig.data import minePageConfig
from apps.user.dao import UserDao
from project.settings import build
from apps.merchant.shop.dao import ShopDao
from apps.education.student.dao import StudentDao
from apps.education.teacher.dao import TeacherDao

class PageConfigViewSet(BasePageConfigViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = PageConfigDao().findAll().select_related('pagee').prefetch_related('clients')
        if self.request.user.role.key == '供应链':
            return _list.filter(Q(id = 1) | Q(id = 83) | Q(id = 84))
        return _list.order_by('-isRoot', '-sort')

    '''根据终端获取界面配置'''
    @action(methods=['post'], detail=False, authentication_classes = [], permission_classes = [])
    def getPageConfigByClientname(self, request):
        params = getRequestParams(request)
        _routerName = params.get('name')
        _configKey = params.get('configKey')
        if not _configKey:
            _configKey = _routerName
        if _routerName == 'custom1':
            _configKey = 'giftSection'
        # 跳过审核特殊处理
        _client = ClientDao().findAll().filter(clientname=params.get('clientname')).first()
        if _client:
            if _client.checking and params.get('build') == str(build):
                if _configKey == 'home' or _configKey == 'custom1' or _configKey == 'custom2' or _configKey == 'giftSection' or _configKey == 'shopItem' or _configKey == 'find':
                    _configKey = "home2"
                elif _configKey == 'itemCate':
                    _configKey = "itemCate2"
            if params.get('channel')=='H5-APPLET':
                if _configKey == 'home':
                    _configKey = "home2"
        _pageConfigs = PageConfigDao().findAll().filter(key=_configKey, clients__in=[_client])
        if not _pageConfigs.exists():
            return Response(response_message('界面配置不存在'))
        _pageConfig = _pageConfigs.first()
        return Response(response_success(PageConfigDetailSerializer(_pageConfig).data))
    
    '''更新信息'''
    @action(methods=['post'], detail=False)
    def updatePageConfig(self, request):
        params = getRequestParams(request)
        _advertList = params.get('advertList')
        if type(_advertList) == list:
            for advert in _advertList:
                if advert.get('id'):
                    serializers = AdvertBaseSerializer(Advert.objects.get(id=advert.get('id')), data=advert, partial=True)
                    if serializers.is_valid():
                        serializers.save()
                    else:
                        print(serializers.errors)
        PageConfigDao().update(params.get('pageConfigId'), params)
        return Response(response_success('更新成功'))
    
    '''获取个人中心配置数据'''
    @action(methods=['post'], detail=False, authentication_classes = [], permission_classes = [])
    def getMinePageConfig(self, request):
        params = getRequestParams(request)
        _userId = params.get('userId')
        itemList = []
        if _userId:
            student = StudentDao().findOneByFilters({"user": _userId})
            teacher = TeacherDao().findOneByFilters({"user": _userId})
            if student:
                itemList.append({
                    'title': "认证资料",
                    'icon': 'account-fill',
                    'color': '#ff9014',
                    'name': 'studentAuth',
                    'size': '26',
                })
            elif teacher:
                itemList.append({
                    'title': "认证资料",
                    'icon': 'account-fill',
                    'color': '#007aff',
                    'name': 'teacherAuth',
                    'size': '26',
                })
            else:
                itemList.append({
                    'title': "身份认证",
                    'icon': 'account-fill',
                    'color': '#39b7a2',
                    'name': 'selectIdentity',
                    'size': '26',
                })
            
        itemList = itemList + minePageConfig.config2
        
        itemListConfig = [{'title': '常用功能', 'items': minePageConfig.config}, {'title': '其他功能', 'items': itemList}, ]
        client = ClientDao().findAll().filter(clientname=params.get('clientname')).first()
        if client.checking and params.get('build') == str(build):
            itemListConfig = itemListConfig = [{'title': '其他功能', 'items': minePageConfig.config2}, ]
        return Response(response_success({'itemListConfig': itemListConfig}))

    '''获取个人中心私有配置数据'''
    @action(methods=['post'], detail=False)
    def getMinePageConfigForPrivate(self, request):
        params = getRequestParams(request)
        configs = []
        if self.request.user.rank.grade >= 1:
            config = {
                        'title': "我的团队",
                        'icon': '/static/common/mine/duoshou.png',
                        'color': '#999',
                        'name': 'duoshou',
                        'size': '26',
                    }
            configs.append(config)
        
        shops = self.request.user.user_shop.all()
        if shops.count() > 0:
            if shops.count() > 1:
                return Response(response_message('您的商户异常，请联系管理员'))
            elif shops.count() == 1:
                shop = shops.first()
                if shop.checkStatus == 'PASS':
                    config = {
                                'title': "商家中心",
                                'icon': '/static/common/mine/duoshou.png',
                                'color': '#999',
                                'name': 'businessCenter',
                                'size': '26',
                            }
                    configs.append(config)
        client = ClientDao().findAll().filter(clientname=params.get('clientname')).first()
        return Response(response_success({'title': '', 'items': configs}))
